package info.xmlprint.core.innerlink;

import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class BaseItem implements Serializable {
	private static final long serialVersionUID = -3245332818390853428L;

	private Map<String, String> valueMap = new HashMap<String, String>();

	/*
	 * each child name must be uniquely
	 */
	private String childrenNames[];

	private String rootElementName;

	public BaseItem(String name) {
		rootElementName = name;
	}

	public String getRootElementName() {
		return rootElementName;
	}

	public String getValueOf(String elementName) {
		String value = valueMap.get(elementName);
		if (value == null) {
			valueMap.put(elementName, "");
			return "";
		}
		return valueMap.get(elementName);
	}

	public Document getXmlDoc() {
		Document doc = DocumentHelper.createDocument();
		Element root = doc.addElement(rootElementName);
		for (String n : childrenNames) {
			root.addElement(n).setText(getValueOf(n));
		}
		return doc;
	}

	protected void setChildrenNames(String names[]) {
		childrenNames = names;
	}

	public void setElementValue(String elementName, String value) {
		valueMap.put(elementName, value);
	}

	public void updateByElement(Element element) {
		if (element == null)
			return;

		rootElementName = element.getName();
		Set<String> set = new HashSet<>();
		Element elem;
		String name;
		for (Object obj : element.selectNodes("*")) {
			elem = (Element) obj;
			name = elem.getName();
			set.add(name);
			setElementValue(name, elem.getText());
		}
		childrenNames = set.toArray(new String[set.size()]);
	} 
}
